<template>
  <div>
    <el-card style="margin-left: 10px;margin-top: 2px;height: 80px">
      <el-form :inline="true" :model="tour" ref="form">
        <el-form-item>
          <el-input size="small" v-model="tour.name " placeholder="请输入要查找的内容"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchInfo">查询</el-button>
          <el-button type="primary" @click="resetFrom('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-left: 10px;margin-top: 2px">
      <el-button type="primary" @click="deleteBatch">批量删除</el-button>
      <el-button type="primary" @click="addTour">添加用户</el-button>
    </el-card>
    <template>
      <div>
        <el-dialog :title="tip" :visible.sync="openTour" :close-on-click-modal="false" width="30%" >


          <el-form ref="elForm" :model="tourForm" size="medium" label-width="100px" :rules="rules">
            <el-form-item label="图片" prop="img">
              <el-upload
                class="upload-demo"
                action="/dev-api/upload"
                :on-success="handleUploadSuccess"
                :on-remove="handleRemove"
                :file-list="fileList"
                :auto-upload="true"
                :limit="1"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="租房形式" prop="name">
              <el-select v-model="tourForm.name" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="户型" prop="lvyoutime">
              <el-input v-model="tourForm.lvyoutime" placeholder="户型" clearable :style="{width: '100%'}"/>
            </el-form-item>


            <el-form-item label="楼层" prop="sights">
              <el-input v-model="tourForm.sights" placeholder="楼层" clearable :style="{width: '100%'}"/>
            </el-form-item>
            <el-form-item label="小区" prop="activiti">
              <el-input v-model="tourForm.activiti" placeholder="小区" clearable :style="{width: '100%'}"/>
            </el-form-item>
            <el-form-item label="位置" prop="metho">
              <el-input v-model="tourForm.metho" placeholder="邮箱" clearable :style="{width: '100%'}"/>
            </el-form-item>
            <el-form-item label="租金" prop="yusuan">
              <el-input type="number" v-model="tourForm.yusuan" placeholder="租金(每月)" clearable :style="{width: '100%'}"/>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="Tour">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </template>

    <el-card style="margin-left: 10px;margin-top: 2px">
      <el-table
        :data="TourInfo"
        style="width: 100%"
        ref="multipleTable"
        border
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column
          type="selection"
          width="55"
          reserve-selection
        />

        <el-table-column
          prop="id"
          label="序号"

        >
        </el-table-column>
        <el-table-column
          prop="img"
          label="图片"
        >
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.img"
              :src="getImageUrl(scope.row.img)"
              :preview-src-list="[getImageUrl(scope.row.img)]"
              style="width: 50px; height: 50px; cursor: pointer"
              fit="cover"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="租房形式"
        >
        </el-table-column>
        <el-table-column
          prop="lvyoutime"
          label="户型">
        </el-table-column>
        <el-table-column
          prop="sights"
          label="楼层">
        </el-table-column>
        <el-table-column
          prop="activiti"
          label="小区">
        </el-table-column>
        <el-table-column
          prop="metho"
          label="位置">
        </el-table-column>
        <el-table-column
          prop="yusuan"
          label="价格">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.$index,scope.row)" type="text" size="small">编辑</el-button>
            <el-button type="text" size="small" @click="deleteTour(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <template>
        <div style="display:flex; align-items: center" class="block" align="center">
          <el-pagination
            @size-change="handleSizeChange"
            :page-sizes="[1, 2, 3]"
            @current-change="handleCurrentChange"
            :page-size="tour.pageSize"
            :current-page="tour.pageNum"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
          <el-button size="small" type="primary" plain @click="toPage">跳转</el-button>
        </div>
      </template>
    </el-card>

  </div>
</template>

<script>
import {addTour, deleteBatch, deleteTour, findAll, updateTour} from '@/api/project/usertaolun'


export default {
  name: "userComment",
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请选择租房形式', trigger: 'change' }
        ],
        lvyoutime: [
          { required: true, message: '请输入户型', trigger: 'blur' }
        ],
        sights: [
          { required: true, message: '请输入楼层', trigger: 'blur' }
        ],
        activiti: [
          { required: true, message: '请输入小区名称', trigger: 'blur' }
        ],
        metho: [
          { required: true, message: '请输入位置', trigger: 'blur' }
        ],
        yusuan: [
          { required: true, message: '请输入租金', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('租金不能为负数'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ]
      },
      options: [{
        value: '整租',
        label: '整租'
      }, {
        value: '合租-主卧',
        label: '合租-主卧'
      },{
        value: '合租-次卧',
        label: '合租-次卧'
      }],
      fileList: [],
      file: null,
      openTour: false,
      tip: "",
      tourForm: {},
      total: 0,
      tour: {
        name: null,
        pageSize: 3,
        pageNum: 1,
      },
      TourInfo: [],
      multipleSelection: []
    }
  },
  methods: {
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 20000) {
        this.tourForm.img = response.data; // 保存文件名到表单
        this.fileList = fileList;
      } else {
        this.$message.error(response.message || '上传失败');
      }
    },
    handleRemove(file, fileList) {
      this.tourForm.fileName = null;
      this.fileList = fileList;
    },
    getImageUrl(filename) {
      if (!filename) return '';
      // 如果已经是完整URL则直接返回
      if (filename.startsWith('https://wanghao1234.oss-cn-hangzhou.aliyuncs.com/g8hms/')) return filename;
      // 否则拼接基础URL（根据你的实际后端配置调整）
      return `https://wanghao1234.oss-cn-hangzhou.aliyuncs.com/g8hms/${filename}`;

    },

    findAll() {
      findAll(this.tour).then(res => {
        if (res.code === 20000) {
          this.TourInfo = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error(ret.message || '获取数据失败');
        }
      })
        .catch(error => {
          this.$message.error('请求失败: ' + error.message);
          console.error(error);
        });
    },
    deleteTour(index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', {

        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTour({id: row.id}).then(res => {
          if (res.code === 20000) {
            this.$message.success('删除成功');
            this.findAll()
          } else {
            this.$message.error(res.message || '删除失败');
          }
        })
          .catch(error => {
            this.$message.error('请求失败: ' + error.message);
            console.error(error);
          });
      })
        .catch(() => {
          this.$message.info('已取消删除');
        });
    },

    searchInfo() {
      this.findAll()
    }
    ,
    resetFrom(formName) {
      this.$refs[formName].resetFields();
      this.tour.name = null
      this.findAll()
    }
    ,
    deleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      this.$confirm('此操作将永久删除[' + this.multipleSelection + '], 是否继续?', '删除用户!', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteBatch(this.multipleSelection)
      }).then(res => {
        if (res.code === 20000) {
          this.$message.success('删除成功');
          this.findAll()
          this.$refs.multipleTable.clearSelection();

        }
      })
        .catch(() => {
          this.$message.info('已取消删除');
        });

    }
    ,
    Tour() {
      this.$refs.elForm.validate(valid => {
        if (!valid) {
          this.$message.error('请填写完整且正确的表单信息');
          return;
        }
        if (this.tip === "添加用户") {
          addTour(this.tourForm).then(res => {
            if (res.code === 20000) {
              this.$message.success('添加成功');
              this.openTour = false
              this.findAll()
            } else {
              this.$message.error(res.message || '添加失败');
            }
          })
            .catch(error => {
              this.$message.error('请求失败: ' + error.message);
              console.error(error);
            });
        } else {
          this.tourForm.tourId = this.TourInfo[0].tourId
          updateTour(this.tourForm).then(res => {
            if (res.code === 20000) {
              this.$message.success('修改成功');
              this.openTour = false
              this.findAll()
            } else {
              this.$message.error(res.message || '修改失败');
            }
          })
            .catch(error => {
              this.$message.error('请求失败: ' + error.message);
              console.error(error);
            })
        }
      })
    }
    ,
    addTour() {
      this.tip = "添加用户";
      this.openTour = true;
      this.tourForm = {};
      this.fileList = [];
      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.elForm) {
          this.$refs.elForm.clearValidate();
        }
      });
    }
    ,
    handleClick(index, row) {
      this.tip = "编辑用户"
      this.tourForm = JSON.parse(JSON.stringify(row));
      this.openTour = true
    }
    ,
    handleSelectionChange(val) {
      this.multipleSelection = []
      for (const index in val) {
        this.multipleSelection.push(val[index].id)// 取出对象id存储到数组
      }
    }
    ,
    handleSizeChange(val) {
      this.tour.pageSize = val
      this.findAll()
    }
    ,
    handleCurrentChange(val) {
      this.tour.pageNum = val
      this.findAll()
    }
    ,
    toPage() {

      this.tour.pageNum = this.$refs.toPage.value
    }
    ,
    close() {
      this.openTour = false

    },
  },

  created() {
    this.findAll()
  }

}
</script>


<style scoped lang="css">

</style>
